<template>
	<view class="content">
		<view>
			<image class="bg-img" src="../../static/index/img3.jpg"></image>
		</view>
		<view class="aubutton">
			<view class="button">
				<button type="primary" lang="zh_CN" @tap="getUserProfile" open-type="getPhoneNumber" @bindgetphonenumber="getPhoneNumber">微信授权登录</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				//开发者Id
				appid: 'wxebadd5f2ffeb172c',
				//AppSecret(小程序密钥)	
				secret: '7b8c959f0ce862abff9aeb432215bca6',
				//临时登录凭证 code
				code: '',
				//名称
				nickName: '',
				//头像地址
				avatarUrl: '',
			}
		},
	    
		methods: {
			getUserProfile() {
				wx.getUserProfile({
					lang: 'zh_CN',
					desc: '用于获取你的个人信息',
					success: res => {
						//判断是否获取到信息
						if (res.userInfo) {
							console.log(res.userInfo)
							console.log(res.userInfo.nickName)
							console.log(res.userInfo.avatarUrl)
							wx.setStorageSync('nickName', res.userInfo.nickName)
							wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
							//获取微信登录接口
							wx.login({
								provider: 'weixin',
								success: res => {
									//把res.code赋值给this.code
									this.code = res.code
									console.log(res)
									console.log(this.code)
									//请求获取openid
									wx.request({
										url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' +
											this.appid + '&secret=' + this.secret +
											'&js_code=' + this.code +
											'&grant_type=authorization_code',
										success: res => {
											//请求后端接口把头像，昵称，openid传入数据库
											console.log('openid:' + res.data.openid);
										}
									})
								}
							})
						} else {
							uni.showToast({
								title: '获取信息失败',
								icon: "error",
								duration: 2000
							})
						}
					},
					fail: err => {
						uni.showToast({
							title: '你已取消登录',
							icon: "error",
							duration: 2000
						})
					}
				})
			},
			getPhoneNumber(e) {
				 console.log(e.detail.code)
				    console.log(e.detail.errMsg)
				    console.log(e.detail.iv)
			},
		}
	}
</script>

<style>
	.content {
		width: 100vw;
		height: 100%;
	}

	.bg-img {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: -1;
	}

	.aubutton {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 15px;
		padding-top: 60%;
	}

	.button {
		width: 100%;
	}
</style>
